package org.singledog.form.builder.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.util.Map;

@Slf4j
public class HttpClientUtil {

    private static final CloseableHttpClient httpClient;
    public static final int TIMEOUT = 3000;

    static {
        httpClient = HttpClients.createDefault();
    }

    /**
     * normal get
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String doGet(String url, Map<String, Object> params) throws Exception {
        URIBuilder uriBuilder = new URIBuilder(url);

        if (!CollectionUtils.isEmpty(params)) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue() == null ? "" : String.valueOf(entry.getValue()));
            }
        }

        HttpGet get = new HttpGet(uriBuilder.build());
        get.setConfig(requestConfig());
        try (CloseableHttpResponse response = httpClient.execute(get);
            InputStream is = response.getEntity().getContent();) {

            String responseMsg = IOUtils.toString(is, "UTF-8");

            int code = response.getStatusLine().getStatusCode();
            if (code != HttpStatus.SC_OK) {
                log.error("HttpClientUtil:doGet:request url:{}, response code:{}, response:{}", uriBuilder.build().toString(), code, responseMsg);
            }

            return responseMsg;
        }
    }

    /**
     * post json
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, Map<String, Object> params) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        if (!CollectionUtils.isEmpty(params)) {
            StringEntity stringEntity = new StringEntity(JSON.toJSONString(params), "UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
        }

        httpPost.setConfig(requestConfig());

        try (CloseableHttpResponse response = httpClient.execute(httpPost);
                InputStream is = response.getEntity().getContent();) {

            String message = IOUtils.toString(is, "UTF-8");
            int code = response.getStatusLine().getStatusCode();
            if (code != HttpStatus.SC_OK) {
                log.error("HttpClientUtil:doPost:request post url: {}, params:{}, response code:{}, message:{}", url, JSON.toJSONString(params), code, message);
            }

            return message;
        }
    }


    private static RequestConfig requestConfig() {
        return RequestConfig.custom()
                .setSocketTimeout(TIMEOUT)
                .setConnectTimeout(TIMEOUT)
                .build();
    }
}
